package com.gjr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 呙境仁
 * @create 2023-07-12 18,17
 */
public class Demo {
    public static void main(String[] args) throws Exception {
          System.out.println(getToken());
        // System.out.println(NewSendMessage ("测试消息","95b5f26c-5ba5-478b-975f-41a1a1f39bc2"));
    }

    static final String SingleMsgURL = "http://10.10.10.76/seeyon/rest/thirdpartyMessage/receive/singleMessage";
    public static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    public static String NewSendMessage(String msg, String tokenId) throws Exception {
        String url = SingleMsgURL + "?token=" + tokenId;
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("thirdpartyRegisterCode", "3002");     //应用编号
        paramMap.put("thirdpartyMessageId", "123344");      //消息的id
        paramMap.put("thirdpartyReceiverId", "001781");     //第三方接受者id
        paramMap.put("creation_date", "2022-08-25 14:11:00");    //发起时间
        paramMap.put("messageURL", "http://www.qq.com");        //pc端连接地址
        paramMap.put("messageH5URL", "http://www.baidu.com");    //移动端连接地址
        paramMap.put("messageContent", msg);   //消息内容
        paramMap.put("thirdpartySenderId", "001781");        //第三方系统发起者id
        paramMap.put("noneBindingSender", "zhangsan");       //oa的发起者登录名
        paramMap.put("noneBindingReceiver", "zhangsan");     //oa的接受者登录名

        String params = gson.toJson(paramMap);
        System.out.println(params);

        String result = doPost(url, params);

        return result;
    }

    /*****
     * - 获取token
     * Resource.TOKENUSER:"fanruan"
     * Resource.TOKENPASSWORD:"f1489e66-90e9-4fa7-8241-cc998cba4051"
     * @return
     */
    public static String getToken() throws Exception { 
        String url = "http://10.10.10.76/seeyon/rest/token";
        Map map = new HashMap<>(); 
        map.put("userName", "fanruan");
        map.put("password", "f1489e66-90e9-4fa7-8241-cc998cba4051");
        String json = JSON.toJSONString(map);
        String result2 = doPost(url, json);
        JSONObject jsonObject = JSON.parseObject(result2);
        String token = jsonObject.getString("id");
        if (token.equals("-1")) {
            return "";
        }else {
            return token;
        }
    }


    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url  地址
     * @param params json格式的参数
     * @return
     */
    public static String doPost(String url, String params) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost( url );// 创建httpPost
        httpPost.setHeader( "Accept", "application/json" );
        httpPost.setHeader( "Content-Type", "application/json" );
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity( params, charSet );
        httpPost.setEntity( entity );
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute( httpPost );
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            } else {
                System.out.println( "请求返回:" + state + "(" + url + ")" );
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
